const express = require('express')
const router = express.Router()


const dbhelper = require('./db/dbhelper')
dbhelper.init()

const path = require('path')

/**
 *  获取类别列表
 *   in: username&devicenum(待定, 暂时不进行验证)
 *   out: { result, message, data}
 */
router.get('/categorys', (req, res)=>{
    console.log('/getcategorys >>> ' + JSON.stringify(req.query))
    dbhelper.queryAppCategoryAll((ret)=>{
        res.header('Cache-Control', 'no-store')
        res.status(200).json(ret)
        // res.type('json')
        // res.json(ret)
    })
})

/**
 *  获取数据
 *  in: cate-code
 *  out: {result, message, data}
 */
router.get('/apps', (req, res)=>{
    console.log('/apps >>> ' + JSON.stringify(req.query))
    dbhelper.queryAppByCateId(req.query.cateid, (ret)=>{
        res.header('Cache-Control', 'no-store')
        res.status(200).json(ret)
    })
})

/**
 *  获取流化启动url~
 *  in: appid
 *  out: {
 *          name: '',
 *          appi: '',
 *          starturl: '',
 *      }
 */
router.get('/start', (req, res)=>{
    console.log('/start >>> ' + JSON.stringify(req.query))
    res.header('Cache-Control', 'no-store')
    res.send('没有部署流化应用服务器')
})

/**
 *  获取资源
 *  in: type&dest
 *  out: stream
 */
router.get('/res', (req, res)=>{
    console.log('/img >>> ' + JSON.stringify(req.query))
    
    switch(parseInt(req.query.type)) {
        case 0:
            res.header('Cache-Control', 'no-store, max-age=0, must-revalidate')
            res.header("Pragma", "no-cache");
            res.status(200)
            res.sendFile(path.join(__dirname, '../../', `/public/imgs/${req.query.dest}`))
            break
        default:
            res.status(404).end()
    }
})

module.exports = {
    router: function() {
        /*if(!isInited) {
            init()
        }*/
        return router
    },
    release: function() {
        /*if(isInited) {
            uninit()
        }*/
    }
}